package cn.rkylin.oms.common.domain;

import cn.rkylin.core.exception.BusinessException;
import cn.rkylin.oms.common.collection.Lists;
import cn.rkylin.oms.common.function.Predicate;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;

import static cn.rkylin.apollo.enums.BusinessExceptionEnum.SEARCH_DATA;
import static cn.rkylin.oms.common.collection.Lists.newArrayList;

public class SortOrderRetriever {

    public static ArrayList<Sort.Order> from(Pageable pageable) throws BusinessException {
        return from(pageable.getSort());
    }

    public static ArrayList<Sort.Order> from(Sort sort) throws BusinessException {
        if (sort != null) {
            ArrayList<Sort.Order> orders = newArrayList(sort.iterator());
            if (hasDangerProperty(orders)) {
                throw new BusinessException(SEARCH_DATA.getC(), "存在非法的排序字段名");
            }
            return orders;
        }

        return null;
    }

    private static boolean hasDangerProperty(ArrayList<Sort.Order> orders) {
        return orders.size() > 0 && Lists.any(orders, new Predicate<Sort.Order>() {
            @Override
            public boolean test(Sort.Order order) {
                return order.getProperty().contains("`");
            }
        });
    }

}
